/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sheresam.springhbnjpa.test2;

import java.awt.Color;
import java.awt.GradientPaint;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

public class AddJFreeChartBarToPDF {

    public void createPDFFromImage(String outputFile) throws IOException, COSVisitorException {
        // the document
        PDDocument doc = null;
        try {
            doc = new PDDocument();

            PDPage page = new PDPage();
            doc.addPage(page);

            JFreeChart chart = AddJFreeChartBarToPDF.generateBarChart1();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ChartUtilities.writeChartAsJPEG(out, chart, 400, 400);//write to outstream
            //create a new inputstream
            InputStream in = new ByteArrayInputStream(out.toByteArray());
            
            PDXObjectImage ximage = new PDJpeg(doc, in);

            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
            
            contentStream.drawImage(ximage, 100, 350);
//            contentStream.drawXObject(ximage, 100, 300, 100, 100);
            
            contentStream.close();
            
            
            
            //page 2
            page = new PDPage();
            doc.addPage(page);

            chart = AddJFreeChartBarToPDF.generateBarChart2();

            out = new ByteArrayOutputStream();
            ChartUtilities.writeChartAsJPEG(out, chart, 400, 400);//write to outstream
            //create a new inputstream
            in = new ByteArrayInputStream(out.toByteArray());
            
            ximage = new PDJpeg(doc, in);

            contentStream = new PDPageContentStream(doc, page, true, true);
            
            contentStream.drawImage(ximage, 100, 350);
//            contentStream.drawXObject(ximage, 100, 300, 100, 100);
            
            contentStream.close();
            
            
            
            
            // page 3
            page = new PDPage();
            doc.addPage(page);

            chart = AddJFreeChartBarToPDF.generateBarChart3();

            out = new ByteArrayOutputStream();
            ChartUtilities.writeChartAsJPEG(out, chart, 400, 400);//write to outstream
            //create a new inputstream
            in = new ByteArrayInputStream(out.toByteArray());
            
            ximage = new PDJpeg(doc, in);

            contentStream = new PDPageContentStream(doc, page, true, true);
            
            contentStream.drawImage(ximage, 100, 350);
//            contentStream.drawXObject(ximage, 100, 300, 100, 100);
            
            contentStream.close();
            doc.save(outputFile);
        } finally {
            if (doc != null) {
                doc.close();
            }
        }
    }

    public static void main(String[] args) {
        AddJFreeChartBarToPDF app = new AddJFreeChartBarToPDF();
        try {
            if (args.length != 1) {
                app.usage();
            } else {
                app.createPDFFromImage(args[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This will print out a message telling how to use this example.
     */
    private void usage() {
        System.err.println("usage: " + this.getClass().getName() + " <output-pdf>");
    }

    public static JFreeChart generateBarChart1() {
        DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
        dataSet.setValue(791, "HumanPopulation", "1750 AD");
        dataSet.setValue(978, "HumanPopulation", "1800 AD");
        dataSet.setValue(1262, "HumanPopulation", "1850 AD");
        dataSet.setValue(1650, "HumanPopulation", "1900 AD");
        dataSet.setValue(2519, "HumanPopulation", "1950 AD");
        dataSet.setValue(6070, "HumanPopulation", "2000 AD");
        
        JFreeChart chart = ChartFactory.createBarChart("World Human & Bird Population growth", "Year", "Population in millions", dataSet,
                PlotOrientation.VERTICAL, false, true, false);
        
        return chart;
    }
    
    public static JFreeChart generateBarChart2() {
        DefaultCategoryDataset dataSet1 = new DefaultCategoryDataset();
        dataSet1.setValue(791, "HumanPopulation", "1750 AD");
        dataSet1.setValue(978, "HumanPopulation", "1800 AD");
        dataSet1.setValue(1262, "HumanPopulation", "1850 AD");
        dataSet1.setValue(1650, "HumanPopulation", "1900 AD");
        dataSet1.setValue(2519, "HumanPopulation", "1950 AD");
        dataSet1.setValue(6070, "HumanPopulation", "2000 AD");
        
//        JFreeChart chart = ChartFactory.createBarChart("World Human & Bird Population growth", "Year", "Population in millions", dataSet1,
//                PlotOrientation.VERTICAL, false, true, false);
        
        dataSet1.setValue(null, "BirdPopulation", "1750 AD");
        dataSet1.setValue(null, "BirdPopulation", "1800 AD");
        dataSet1.setValue(null, "BirdPopulation", "1850 AD");
        dataSet1.setValue(null, "BirdPopulation", "1900 AD");
        dataSet1.setValue(null, "BirdPopulation", "1950 AD");
        dataSet1.setValue(null, "BirdPopulation  ", "2000 AD");
        
        DefaultCategoryDataset dataSet2 = new DefaultCategoryDataset();
        dataSet2.setValue(null, "HumanPopulation", "1750 AD");
        dataSet2.setValue(null, "HumanPopulation", "1800 AD");
        dataSet2.setValue(null, "HumanPopulation", "1850 AD");
        dataSet2.setValue(null, "HumanPopulation", "1900 AD");
        dataSet2.setValue(null, "HumanPopulation", "1950 AD");
        dataSet2.setValue(null, "HumanPopulation", "2000 AD");
        
        dataSet2.setValue(600, "BirdPopulation", "1750 AD");
        dataSet2.setValue(800, "BirdPopulation", "1800 AD");
        dataSet2.setValue(1300, "BirdPopulation", "1850 AD");
        dataSet2.setValue(1700, "BirdPopulation", "1900 AD");
        dataSet2.setValue(2100, "BirdPopulation", "1950 AD");
        dataSet2.setValue(4000, "BirdPopulation", "2000 AD");

        
        final CategoryAxis domainAxis = new CategoryAxis("Year");
        final NumberAxis rangeAxis = new NumberAxis("Population in millions");
        final BarRenderer renderer1 = new BarRenderer();
        final CategoryPlot plot = new CategoryPlot(dataSet1, domainAxis, rangeAxis, renderer1) {
            
            /**
             * 
             */
            private static final long serialVersionUID = -2763990347369014345L;

            /**
             * Override the getLegendItems() method to handle special case.
             *
             * @return the legend items.
             */
            public LegendItemCollection getLegendItems() {

                final LegendItemCollection result = new LegendItemCollection();

                final CategoryDataset data = getDataset();
                if (data != null) {
                    final CategoryItemRenderer r = getRenderer();
                    if (r != null) {
                        final LegendItem item = r.getLegendItem(0, 0);
                        result.add(item);
                    }
                }

                // the JDK 1.2.2 compiler complained about the name of this
                // variable 
                final CategoryDataset dset2 = getDataset(1);
                if (dset2 != null) {
                    final CategoryItemRenderer renderer2 = getRenderer(1);
                    if (renderer2 != null) {
                        final LegendItem item = renderer2.getLegendItem(1, 1);
                        result.add(item);
                    }
                }

                return result;

            }
            
        };
        
        final JFreeChart chart = new JFreeChart("Dual Axis Bar Chart", plot);
        chart.setBackgroundPaint(Color.white);
//        chart.getLegend().setAnchor(Legend.SOUTH);
        plot.setBackgroundPaint(new Color(0xEE, 0xEE, 0xFF));
        plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
        plot.setDataset(1, dataSet2);
        plot.mapDatasetToRangeAxis(1, 1);
        final ValueAxis axis2 = new NumberAxis("Secondary");
        plot.setRangeAxis(1, axis2);
        plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
        final BarRenderer renderer2 = new BarRenderer();
        plot.setRenderer(1, renderer2);
        
        return chart;
    }
    
    
    public static JFreeChart generateBarChart3() {
        
        // row keys...
        final String series1 = "First";
        final String series2 = "Second";
        final String series3 = "Third";

        // column keys...
        final String category1 = "Category 1";
        final String category2 = "Category 2";
        final String category3 = "Category 3";
        final String category4 = "Category 4";
        final String category5 = "Category 5";

        // create the dataset...
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        dataset.addValue(1.0, series1, category1);
        dataset.addValue(4.0, series1, category2);
        dataset.addValue(3.0, series1, category3);
        dataset.addValue(5.0, series1, category4);
        dataset.addValue(5.0, series1, category5);

        dataset.addValue(5.0, series2, category1);
        dataset.addValue(7.0, series2, category2);
        dataset.addValue(6.0, series2, category3);
        dataset.addValue(8.0, series2, category4);
        dataset.addValue(4.0, series2, category5);

        dataset.addValue(4.0, series3, category1);
        dataset.addValue(3.0, series3, category2);
        dataset.addValue(2.0, series3, category3);
        dataset.addValue(3.0, series3, category4);
        dataset.addValue(6.0, series3, category5);
        
    
        
        // create the chart...
        final JFreeChart chart = ChartFactory.createBarChart(
            "Bar Chart Demo",         // chart title
            "Category",               // domain axis label
            "Value",                  // range axis label
            dataset,                  // data
            PlotOrientation.VERTICAL, // orientation
            true,                     // include legend
            true,                     // tooltips?
            false                     // URLs?
        );

        // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

        // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

        // get a reference to the plot for further customisation...
        final CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);

        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        // disable bar outlines...
        final BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);
        
        // set up gradient paints for series...
        final GradientPaint gp0 = new GradientPaint(
            0.0f, 0.0f, Color.blue, 
            0.0f, 0.0f, Color.lightGray
        );
        final GradientPaint gp1 = new GradientPaint(
            0.0f, 0.0f, Color.green, 
            0.0f, 0.0f, Color.lightGray
        );
        final GradientPaint gp2 = new GradientPaint(
            0.0f, 0.0f, Color.red, 
            0.0f, 0.0f, Color.lightGray
        );
        renderer.setSeriesPaint(0, gp0);
        renderer.setSeriesPaint(1, gp1);
        renderer.setSeriesPaint(2, gp2);

        final CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(
            CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
        );
        // OPTIONAL CUSTOMISATION COMPLETED.
        
        return chart;
        
    }

    public static void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024]; // Adjust if you want
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    }
}
